﻿using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Devv.Core.Erroo;
using Devv.Core.Utils;
using Devv.FreshTracker.Entity;

namespace Devv.FreshTracker
{
	static class Program
	{
		#region Forms and properties

		public static Boolean PreventRunning { get; set; }
		public static Boolean Closing { get; set; }
		public static MainForm MainFormObj;

		#endregion

		#region Methods

		[STAThread]
		static void Main()
		{
			AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
			{
				String resourceName = "Devv.FreshTracker.Controller.Bin.Release." + new AssemblyName(args.Name).Name + ".dll";

				using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
				{
					Byte[] assemblyData = new Byte[stream.Length];
					stream.Read(assemblyData, 0, assemblyData.Length);

					return Assembly.Load(assemblyData);
				}
			};

			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);

			Startup();

			if (PreventRunning)
			{
				Application.Exit();
				return;
			}

			Application.Run(MainFormObj);
		}

		private static void Startup()
		{
			MainFormObj = new MainForm();

			try
			{
				Maintenance.Log("Starting app.", true);

				Closing = false;
				PreventRunning = false;

				App.OnFirstExecution += FirstExecution;
				LocalCache.OnSessionUploadFailed += SessionUploadFailed;
				LocalCache.OnFailingToUploadData += FailingToUploadData;
				LocalCache.OnFailingToSyncManyTimes += FailingToSyncManyTimes;
				AutoTracking.OnAutoTimerTick += WindowsMonitor.GetActiveWindowTitle;

				App.Init(Application.ExecutablePath);

				Maintenance.Log("APP STARTED!", true);
			}
			catch (Exception ex)
			{
				ErrorHandler.Handle(ex);

				MessageBox.Show(Messages.AppStartupError, Messages.Error, MessageBoxButtons.OK, MessageBoxIcon.Warning);
			}
		}

		#endregion

		#region Show and hide forms

		public static void ShowOptionsForm()
		{
			foreach (Form form in Application.OpenForms)
			{
				if (form.Name == "OptionsForm")
				{
					form.BringToFront();
					form.Focus();
					return;
				}
			}

			OptionsForm oForm = new OptionsForm();
			oForm.Show();
		}

		public static void ShowRulesForm(Boolean showNotes = false)
		{
			foreach (Form form in Application.OpenForms)
			{
				if (form.Name == "RulesForm")
				{
					form.BringToFront();
					form.Focus();

					if (showNotes)
					{
						((RulesForm)form).ShowNotes();
					}

					return;
				}
			}

			RulesForm rForm = new RulesForm();
			rForm.Show();

			if (showNotes)
			{
				rForm.ShowNotes();
			}
		}

		#endregion

		#region App events

		public static void LicenseInvalid(String message)
		{
			PreventRunning = true;

			MessageBox.Show(message);
		}

		public static void FirstExecution()
		{
			String dir = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu);
			String app = Assembly.GetEntryAssembly().Location;
			String icon = app.Replace('\\', '/');
			String path = dir + "\\" + ConfigUtil.GetConfig("Devv.AppName");

			if (File.Exists(path + ".url") || Directory.Exists(path))
			{
				return;
			}

			if (MessageBox.Show(Messages.FirstExecutionWindows, Messages.Welcome, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
			{
				using (StreamWriter writer = new StreamWriter(path + ".url"))
				{
					writer.WriteLine("[InternetShortcut]");
					writer.WriteLine("URL=file:///" + app);
					writer.WriteLine("IconIndex=0");
					writer.WriteLine("IconFile=" + icon);

					writer.Flush();
				}
			}
		}

		public static void SessionUploadFailed(Session s)
		{
			MessageBox.Show(Messages.SessionUploadFailed + Environment.NewLine + Environment.NewLine + s, Messages.Warning);
		}

		public static void FailingToUploadData()
		{
			if (MessageBox.Show(Messages.FailingToUploadData, Messages.Warning, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
			{
				ShowOptionsForm();
			}
		}

		public static void FailingToSyncManyTimes()
		{
			if (MessageBox.Show(Messages.FailingToSyncManyTimes, Messages.Warning, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
			{
				LocalCache.Clear(false);

				ShowOptionsForm();
			}
		}
		
		#endregion
	}
}